package com.itheima;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/Servlet01")
public class Servlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建输入流对象，关联要下载的文件
        ServletContext servletContext = getServletContext();
        String realPath = servletContext.getRealPath("/img/airplane.png");
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(realPath));
        //2.设置响应支持的类型
      //  resp.setHeader("Context-Type","application/octet-stream");
        //3.设置响应头以支持的方式下载
     //   resp.setHeader("Context-Disposition","attachment;filename=airplane.png");
        //4.获取字节输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] arr=new byte[1024];
        int len ;
        while ((len=bis.read(arr))!=-1){
            outputStream.write(arr,0,len);
        }
        bis.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
